今天要使用 System.nanoTime() 量測程式執行時間,
比較同步掃描 和 多執行緒掃描 的效能差異,
學會用「數據」而不是「感覺」來判斷程式快或慢
System.nanoTime() 的用途
用來量測程式執行的「時間差」。
單位是奈秒 (ns),比 currentTimeMillis() 更精準,不會受到系統時間調整影響。
package day1;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Day21demo {
private static boolean isPortOpen(String host, int port, int timeout) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), timeout);
return true; // 連得上 → 開啟
} catch (Exception e) {
return false; // 連不上 → 關閉
}
}
private static void syncScan(String host, int startPort, int endPort) {
    for (int port = startPort; port <= endPort; port++) {
        if (isPortOpen(host, port, 200)) {
            System.out.println("[同步] Port " + port + " 開啟");
        }
    }
}
private static void multiThreadScan(String host, int startPort, int endPort, int threads ){
    ExecutorService executorService = Executors.newFixedThreadPool(threads);
    for (int port = startPort; port <= endPort; port++) {
        int p =port;
        executorService.submit(() -> {
            if (isPortOpen(host, p, 200)) {
                System.out.println("[多執行緒] Port " + p + " 開啟");
            }
        });
    }
    executorService.shutdown();
    while (!executorService.isTerminated()) {}
}
public static void main(String[] args) {
    String host = "127.0.0.1";
    int startPort = 1;
    int endPort = 200;
    long startSync = System.nanoTime();
    syncScan(host, startPort, endPort);
    long endSync = System.nanoTime();
    System.out.println("同步掃描耗時" + (endSync - startSync)/1_000_000.0 + "ms/n");
    long startMulti = System.nanoTime();
    multiThreadScan(host, startPort, endPort, 10); // 開 10 個執行緒
    long endMulti = System.nanoTime();
    System.out.println("多執行緒掃描耗時:" + (endMulti - startMulti) / 1_000_000.0 + " ms");
}
}
程式碼中
long startSync = System.nanoTime();
System.nanoTime():抓取現在的「時間點」(單位奈秒,1 奈秒 = 十億分之一秒)。
回傳型態是 long(因為數字很大,可能超過 int)。
startSync:變數名稱,用來記錄 同步掃描開始的時間點。
syncScan(host, startPort, endPort);
呼叫方法 syncScan()
傳入的參數:
host → 目標主機 (例如 "localhost" 或 "127.0.0.1")
startPort → 起始 port (例如 1)
endPort → 結束 port (例如 100)
這裡就是「實際做同步掃描」的地方,會一個一個 port 檢查。
long endSync = System.nanoTime();
再次呼叫 System.nanoTime(),這次是 掃描結束的時間點。
存到 endSync。
總結:先記錄「開始時間」,
執行一段要測試的程式(這裡是同步掃描),
最後記錄「結束時間」。

今天學到了
System.nanoTime() 的用途
用來量測程式執行的「時間差」。
單位是奈秒 (ns),比 currentTimeMillis() 更精準,不會受到系統時間調整影響。
常見用法:
long start = System.nanoTime();
// 執行某段程式
long end = System.nanoTime();
long duration = end - start; // 執行時間差
時間差的單位轉換
奈秒 (ns) → 毫秒 (ms) :除以 1_000_000.0
這樣更方便觀察效能比較。
同步 vs 多執行緒效能比較的做法
用 nanoTime() 分別包住同步掃描與多執行緒掃描。
觀察兩者耗時,了解「多執行緒在 I/O-bound 任務 (像 port 掃描) 通常比較快」。
程式效能測試的基本流程
開始時間 → 執行程式 → 結束時間 → 相減計算 → 印出結果。
以前可能只知道程式「能跑就好」,但今天開始體會到同一段程式可以有不同的速度。
nanoTime() 就像是一個「碼錶」,能精準幫助我們比較效能。
透過今天的練習,已經可以開始分析「同步」和「多執行緒」在效能上的差異。
最重要的是學會了怎麼科學地量測程式速度,而不是「憑感覺」。